<template>
	<view class="main">
		<u-navbar title-color="#717171" :background="{ backgroundColor: '#ffffff' }" :back-text-style="{color: '#fff'}" title="选择音乐"></u-navbar>
		<!-- 顶部选项卡 -->
		<scroll-view id="nav-bar" class="nav-bar" scroll-x scroll-with-animation :scroll-left="scrollLeft">
			<view v-for="(item,index) in tabBars" :key="item.categoryId" class="nav-item" :class="{current: index === tabCurrentIndex}"
			 :id="'tab'+index" @click="changeTab(index,item.categoryId)">{{item.categoryTitle}}</view>
		</scroll-view>
		<!-- 下拉刷新组件 -->
		<mix-pulldown-refresh ref="mixPulldownRefresh" class="panel-content" :top="235" @refresh="onPulldownReresh"
		 @setEnableScroll="setEnableScroll">
			<!-- 内容部分 -->
			<swiper id="swiper" class="swiper-box" :duration="300" :current="tabCurrentIndex" @change="changeTab">
				<swiper-item v-for="(tabItem,ids) in tabBars" :key="ids">
					<scroll-view class="panel-scroll-box" :scroll-y="enableScroll" @scrolltolower="loadMore">
						<u-empty v-if="tabItem.newsList.length==0" text="列表为空" mode="list"></u-empty>
						<view class="music-concen" v-for="(item, index) in tabItem.newsList" :key="index">
							<view @click="navToDetails(item,index,ids)" :class="['music-img', item.show==true?'img01':'']">
								<image :src="'https://music-asean.oss-cn-hongkong.aliyuncs.com'+item.cover" mode=""></image>
							</view>
							<view @click="navToDetails(item,index,ids)" class="music-text">
								<view class="txt">{{item.title}}</view>
								<view>{{item.singer}}</view>
							</view>
							<view class="music-button">
								<u-icon @click="favoriteClick(item)" style="margin-right: 10rpx;" class="yticon active" :name="item.favorite===true?'star-fill':'star'"
								 :color="item.favorite===true?'#ec706b':'#b4b4b4'" size="50"></u-icon>
								<button v-show="item.show==true" size="mini" type="default">使用</button>
								<text v-show="item.show==false">{{item.duration}}</text>
							</view>
						</view>
						<!-- 上滑加载更多组件 -->
						<mix-load-more :status="tabItem.loadMoreStatus"></mix-load-more>
					</scroll-view>
				</swiper-item>
			</swiper>
		</mix-pulldown-refresh>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import utils from '@/components/shoyu-date/utils.filter.js';
	import mixAdvert from '@/components/mix-advert/vue/mix-advert';
	import mixPulldownRefresh from '@/components/mix-pulldown-refresh/mix-pulldown-refresh';
	import mixLoadMore from '@/components/mix-load-more/mix-load-more';
	let windowWidth = 0,
		scrollTimer = false,
		tabBar;
	export default {
		components: {
			mixPulldownRefresh,
			mixLoadMore,
			mixAdvert
		},
		data() {
			return {
				utils: utils,
				tabCurrentIndex: 0, //当前选项卡索引
				scrollLeft: 0, //顶部选项卡左滑距离
				enableScroll: true,
				tabBars: [],
				page_index: 1, //当前页数
				innerAudioContext: '' //播放函数
			}
		},
		onLoad() {
			// 获取屏幕宽度
			windowWidth = uni.getSystemInfoSync().windowWidth;
			this.loadTabbars();
		},

		onBackPress() {
			if (this.innerAudioContext) this.innerAudioContext.destroy()
		},
		methods: {
			//添加收藏
			async favoriteClick(item) {
				const res = await this.$myRequest({
					url: '/user/favorite',
					method: 'post',
					header: {},
					data: {
						info_id: item.music_id,
						type: 2
					}
				})
				let operation = ''
				res.data.operation == 1 ? operation = this.$i18n.messages[this.$i18n.locale].pressrelease.Collectionok : operation =
					this.$i18n.messages[this.$i18n.locale].pressrelease.CanceCollection
				this.$refs.uToast.show({
					title: operation,
					type: 'success'
				})
				if (res.code == 200) item.favorite = !item.favorite
			},
			//计算时长
			s_to_hs(s) {
				//计算分钟
				//算法：将秒数除以60，然后下舍入，既得到分钟数
				var h;
				h = Math.floor(s / 60);
				//计算秒
				//算法：取得秒%60的余数，既得到秒数
				s = s % 60;
				//将变量转换为字符串
				h += '';
				s += '';
				//如果只有一位数，前面增加一个0
				h = (h.length == 1) ? '0' + h : h;
				s = (s.length == 1) ? '0' + s : s;
				return h + ':' + s;
			},
			//获取分类
			async loadTabbars() {
				const res = await this.$myRequest({
					url: '/category/get-music-type',
					header: {}
				})
				let tabList = res.data;
				tabList.forEach(item => {
					item.newsList = [];
					item.loadMoreStatus = 0; //加载更多 0加载前，1加载中，2没有更多了
					item.refreshing = 0; //动画
				})

				this.tabBars = tabList;
				this.loadNewsList('add');
			},
			//音乐列表 
			async loadNewsList(type) {
				let tabItem = this.tabBars[this.tabCurrentIndex];
				let categoryId = tabItem.categoryId //频道id
				let page_size = 15 //每页显示多少条数据
				let page_index = this.page_index //当前第几页
				const res = await this.$myRequest({
					url: '/category/get-music-list/' + categoryId + '/' + page_size + '/' + page_index,
					header: {}
				})
				//type add 加载更多 refresh下拉刷新
				if (type === 'add') {
					if (tabItem.loadMoreStatus === 2) {
						return;
					}
					tabItem.loadMoreStatus = 1;
				}
				// #ifdef APP-PLUS
				else if (type === 'refresh') {
					tabItem.refreshing = true;
				}
				// #endif

				//setTimeout模拟异步请求数据
				setTimeout(() => {
					let list = res.data;
					if (type === 'refresh') {
						tabItem.newsList = []; //刷新前清空数组
					}
					list.forEach(item => {
						item.show = false
						item.duration = this.s_to_hs(item.duration)
						tabItem.newsList.push(item);
					})
					//下拉刷新 关闭刷新动画
					if (type === 'refresh') {
						this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
						// #ifdef APP-PLUS
						tabItem.refreshing = false;
						// #endif
						tabItem.loadMoreStatus = 0;
					}
					//上滑加载 处理状态
					if (type === 'add') {
						tabItem.loadMoreStatus = tabItem.newsList.length > 40 ? 2 : 0;
						this.page_index++
					}
				}, 600)
			},
			//试听音乐
			navToDetails(item, index, id) {
				for (let i = 0; i < this.tabBars.length; i++) {
					const tabLSIT = this.tabBars[i].newsList.map(item => {
						item.show = false
						return item
					})
				}
				if (this.innerAudioContext) this.innerAudioContext.destroy()
				let srcs = 'https://music-asean.oss-cn-hongkong.aliyuncs.com' + item.music_file;
				this.tabBars[id].newsList[index].show = true;
				this.innerAudioContext = uni.createInnerAudioContext();
				this.innerAudioContext.autoplay = true;
				this.innerAudioContext.src = srcs
				this.innerAudioContext.onPlay(() => {
					console.log('开始播放');
				});
				this.innerAudioContext.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
			},

			//下拉刷新
			onPulldownReresh() {
				this.innerAudioContext.destroy()
				/* this.loadNewsList('refresh'); */
				let tabItem = this.tabBars[this.tabCurrentIndex];
				this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
				// #ifdef APP-PLUS
				tabItem.refreshing = false;
				// #endif
				tabItem.loadMoreStatus = 0;

			},
			//上滑加载
			loadMore() {
				this.loadNewsList('add');
			},
			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable) {
				if (this.enableScroll !== enable) {
					this.enableScroll = enable;
				}
			},

			//tab切换
			async changeTab(e, channelId) {
				if (scrollTimer) {
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if (typeof e === 'object') {
					index = e.detail.current
				}
				if (typeof tabBar !== 'object') {
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if (i === index) {
						nowWidth = result.width;
					}
				}
				if (typeof e === 'number') {
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index;
				}
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(() => {
					if (width - nowWidth / 2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth / 2 - windowWidth / 2;
					} else {
						this.scrollLeft = 0;
					}
					if (typeof e === 'object') {
						this.tabCurrentIndex = index;
					}
					this.tabCurrentIndex = index;


					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					if (this.tabCurrentIndex !== 0 && tabItem.loaded !== true) {
						this.loadNewsList('add');
						tabItem.loaded = true;
					}
				}, 10)

			},
			//获得元素的size
			getElSize(id) {
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
		}
	}
</script>

<style lang='scss' scoped>
	page,
	.content {
		background-color: #f8f8f8;
		height: 100%;
		overflow: hidden;
	}

	/* 顶部tabbar */
	.nav-bar {
		position: relative;
		z-index: 10;
		height: 90upx;
		white-space: nowrap;
		box-shadow: 0 2upx 8upx rgba(0, 0, 0, .06);
		background-color: #fff;

		.nav-item {
			display: inline-block;
			/* width: 120upx; */
			height: 90upx;
			padding: 0 20rpx;
			text-align: center;
			line-height: 90upx;
			font-size: 30upx;
			color: #303133;
			position: relative;

			&:after {
				content: '';
				width: 0;
				height: 0;
				border-bottom: 4upx solid #ed4141;
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				transition: .3s;
			}
		}

		.current {
			color: #ed4141;

			&:after {
				width: 50%;
			}
		}
	}

	.swiper-box {
		height: 100%;
	}

	.panel-scroll-box {
		height: 100%;

		.panel-item {
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}

	.music-concen {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 150rpx;
		border-bottom: 1rpx solid #d4d4d4;

		.music-img {
			flex: 2;
			width: 130rpx;
			height: 130rpx;
			padding: 0 10rpx;

			image {
				width: 130rpx;
				height: 130rpx;
				border-radius: 50px;
			}
		}

		.music-text {
			flex: 6;

			view {
				font-size: 25rpx;
				color: #b1b1b1;
			}

			.txt {
				margin-bottom: 10rpx;
				font-size: 35rpx;
				color: #1e1e1e;
				font-weight: 600;
			}
		}

		.music-button {
			flex: 3;
			text-align: right;
			padding-right: 30rpx;

			button {
				color: #fff;
				background-color: #ed4141;
			}

			text {
				color: #ababab;
				line-height: 50rpx;
			}
		}
	}

	.img01 {
		display: block;
		animation: rotate 6s linear infinite;
	}

	@keyframes rotate {
		0% {
			transform: rotateZ(0deg);
			/*从0度开始*/
		}

		100% {
			transform: rotateZ(360deg);
			/*360度结束*/
		}
	}
</style>
